import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ReviewBackService } from './review-back.service';
import { SearchRemindComponent } from '../search-remind/search-remind.component'
import { DataService } from '../../../../../services/data.service';
import * as _ from "lodash";
@Component({
  selector: 'app-review-back',
  templateUrl: './review-back.component.html',
  styleUrls: ['./review-back.component.scss'],
  providers: [ReviewBackService]
})
export class ReviewBackComponent implements OnInit {

  // 查看提醒人信息modal
  @ViewChild("searchRemind", { read: ViewContainerRef })
  searchRemind: ViewContainerRef;
  searchRemindComponent: ComponentRef<SearchRemindComponent>;

  constructor(
    public reviewBackService: ReviewBackService,
    public resolver: ComponentFactoryResolver,
    public dataService: DataService
  ) { }

  // 提醒人展示字段
  public displayName: any;

  // 控制显示的提示信息，1为复核通过，2为返回,3、4为不需要上部列表时传入，3为审核通过，4为返回
  public showTip: any;
  //短信提醒
  public sSMSFlag: any = false;
  //邮件提醒
  public sEmailFlag: any = false;
  // 接受传过来的对象
  public receivedItem: any;

  // 列表数据
  public listData: any;

  // post数据
  public postbody: any = {
    auditContentBean: {
      auditOpr: '',
      title: '',
      content: '',
      remark: ''
    },
    pmsNqdiiJournalExtList: []
  }

  ngOnInit() {
    console.log(this.receivedItem);
    if (this.showTip == 1 || this.showTip == 2) {
      this.loadList();
    }
    this.defaultValue()
    // this.postbody.auditContentBean.remark = this.receivedItem.sOprMark
    this.dataService.reminderEmitter = new EventEmitter();
    this.dataService.reminderEmitter.subscribe((value) => {
      if (value) {
        this.postbody.auditContentBean.auditOpr = _.concat(value.sMbrName, value.sUsername).join(',');

        // console.log(this.postbody.auditContentBean.auditOpr);
        this.displayName = _.concat(value.sMbrName, value.sRealname)
        // console.log(this.displayName);
      }
    })
  }


  // 加载列表
  loadList() {
    let getbody = {
      pageIndex: 0,
      pageSize: 0,
      nBatchNo: this.receivedItem[0].nBatchNo,
      nNjId: this.receivedItem[0].nNjId
    }
    this.reviewBackService.list(getbody).subscribe((data) => {
      if (data) {
        console.log(data)
        this.listData = data.list;
      }
    })
  }

  // 关闭提醒人modal
  closeModal() {
    if (this.searchRemindComponent) {
      this.searchRemindComponent.destroy();
    }
    console.log(this.receivedItem)
    let unlockBody = {
      nIdList: [this.receivedItem[0].nId]
    }
    window['$']('#modal2').modal('hide');
    window['$']('#modal5').modal('hide');
    window['$']('#modal6').modal('hide');
    this.reviewBackService.unlock(unlockBody).subscribe((data) => {



    })


  }
  // 显示提醒人modal
  showModal(showTip) {
    if (this.searchRemindComponent && this.searchRemindComponent.instance) {
      this.searchRemindComponent.destroy();
    }

    // 动态创建组件的实例
    const searchRemindComponent = this.resolver.resolveComponentFactory(SearchRemindComponent);
    this.searchRemindComponent = this.searchRemind.createComponent(searchRemindComponent);
    window['$']('#searchRemind').modal('show');

  }
  // 执行审核/撤回操作 
  saveStatus(operate) {
    let that = this
    window["swal"](
      {
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        title: "提示",
        text: "请确认是否执行" + operate + "操作？"
      },
      function (isConfirm) {
        if (isConfirm) {
          // console.log(this.showTip)
          if (that.showTip == 1 || that.showTip == 2) {
            that.postbody.pmsNqdiiJournalExtList = that.receivedItem
            if (operate == '审核') {
              _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
                item.sOprState = 2;
              })
              // that.receivedItem.sOprState = 2;
            }
            if (operate == '返回') {
              _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
                item.sOprState = 3;
              })
              // that.receivedItem.sOprState = 3;
            }
            // delete that.receivedItem.sOprDateStart;
            // delete that.receivedItem.sOprDateEnd;
            // delete that.receivedItem.nBatchNoStart;
            // delete that.receivedItem.nBatchNoEnd;
            // delete that.receivedItem.nBatchNumber;

            _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
              delete item.isChecked;
            })
          }

          if (that.showTip == 3 || that.showTip == 4) {
            _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
              console.log(item);
              if (operate == '审核') {
                // item.sOprState = 2;
                _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
                  item.sOprState = 2;
                })
              }
              if (operate == '返回') {
                _.forEach(that.postbody.pmsNqdiiJournalExtList, item => {
                  item.sOprState = 3;
                })
                // item.sOprState = 3;
              }
              delete item.isChecked
            })
          }
          that.postbody.pmsNqdiiJournalExtList = Array.from(new Set(that.postbody.pmsNqdiiJournalExtList))
          let postBody = _.cloneDeep(that.postbody);
          //判断选中的对象的sFundType是否为数组
          _.forEach(postBody.pmsNqdiiJournalExtList, item => {
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
          })
          console.log(postBody);
          that.reviewBackService.audit(postBody).subscribe((data) => {
            if (data) {

              console.log(data);
              window['swal']("成功", operate + "成功 !", "success")
              that.dataService.nQDIIReviewBackEmitter.emit('nQDIIReviewBack');
              window['$']('#modal2').modal('hide');
              window['$']('#modal4').modal('hide');
              window['$']('.modal-backdrop').remove()
            } else {
              window['swal']("提示", operate + "操作失败!", "warning")
            }
          })
        }
      }
    );
  }

  //获取默认模板接口
  defaultValue() {
    let that = this;
    let getBody: any = {
      "sButtonId": '70192@nqdii_monitor_check'
    }
    this.reviewBackService.defaultValue(getBody).subscribe(data => {
      if (data) {
        console.log(data);
        if (Array.isArray(data)) {
          if (data.length > 1) {
            that.displayName = data[0].sContent;
            that.postbody.auditContentBean.auditOpr = data[0].sContent;
            if (data[0].sSMSFlag == 'true') {
              that.sSMSFlag = true;
            }
            if (data[0].sEmailFlag == 'true') {
              that.sEmailFlag = true;
            }
            that.postbody.auditContentBean.content = data[1].sContent;
            that.postbody.auditContentBean.title = data[1].sRemindTitle;
          }
        }
      }
    })
  }
  //设置默认接口
  setDefault() {
    let that = this;
    let postBody = _.cloneDeep(this.postbody.auditContentBean);
    postBody['sButtonId'] = '70192@nqdii_monitor_check';
    postBody['sEmailFlag'] = _.cloneDeep(this.sEmailFlag);
    postBody['sEmailContent'] = _.cloneDeep(postBody.content);
    postBody['sSMSFlag'] = _.cloneDeep(this.sSMSFlag);
    postBody['sSMSContent'] = _.cloneDeep(postBody.content);
    delete postBody.content;
    if (postBody.sEmailFlag) {
      postBody.sEmailFlag = 'Y'
    } else {
      postBody.sEmailFlag = 'N'
    }
    if (postBody.sSMSFlag) {
      postBody.sSMSFlag = 'Y'
    } else {
      postBody.sSMSFlag = 'N'
    }
    console.log(postBody)
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否设置默认" + "</div>",
      html: true
    },
      function (isConfirm) {
        if (isConfirm) {
          that.reviewBackService.setDefault(postBody).subscribe(data => {
            if (data) {
              window['swal']("提示", "设置默认成功", "success");
            }

          })
        }
      });
    console.log(postBody)
  }

}
